<template>
  <div class="task_form_dialog">
    <el-dialog
      v-model="visible"
      :title="`${isEdit ? '编辑' : '新建'}角色`"
      :append-to-body="true"
      :show-close="false"
      :close-on-click-modal="false"
      top="30vh"
      center
      width="500px"
    >
      <div v-loading="dialogLoading" class="dialog_container">
        <div class="form_box f_1">
          <el-form
            ref="formRef"
            :rules="rules"
            :model="form"
            label-width="90px"
            size="small"
          >
            <el-form-item label="角色名" prop="roleName">
              <el-input
                v-model.trim="form.roleName"
                size="small"
                placeholder="请输入"
              ></el-input>
            </el-form-item>

            <el-form-item label="是否使用" prop="asUse">
              <el-switch
                v-model="form.asUse"
                :inline-prompt="true"
                active-text="是"
                inactive-text="否"
              />
            </el-form-item>
          </el-form>
        </div>
      </div>
      <template #footer>
        <div class="dialog_footer">
          <el-button
            type="primary"
            @click="handleConfirm"
            :loading="confirmBtnLoading"
            size="small"
          >
            保存
          </el-button>
          <el-button @click="close" size="small">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, getCurrentInstance } from "vue";
import { ElMessage } from "element-plus";

const initFormData = () => {
  return {
    id: null,
    roleName: null,
    orgId: null,
    asUse: true,
  };
};

export default {
  name: "RoleFormDialog",
  components: {},
  props: {},
  setup(props, context) {
    const { proxy } = getCurrentInstance();
    const $api = proxy.$api;

    const isEdit = ref(false);
    // 弹框是否显示
    const visible = ref(false);
    // 是否开启整个弹框loading（开启时无法关闭弹框）
    const dialogLoading = ref(false);
    // 确认按钮loading（开启时可以关闭弹框）
    const confirmBtnLoading = ref(false);
    // 表单的引用
    const formRef = ref(null);
    // 表单数据
    const form = reactive(initFormData());
    // 表单校验规则
    const rules = reactive({
      roleName: [{ required: true, message: "请输入角色名", trigger: "blur" }],
      // asUse: [
      //   { required: true, message: "请选择是否使用", trigger: "blur" },
      // ],
    });

    const handleConfirm = () => {
      formRef.value.validate((valid) => {
        if (valid) {
          confirmBtnLoading.value = true;
          $api.role
            .saveOrUpdate(form)
            .then((res) => {
              confirmBtnLoading.value = false;
              ElMessage.success("操作成功！");
              // 触发事件，把数据传递给父组件
              context.emit("refresh");
              close();
            })
            .catch((err) => {
              confirmBtnLoading.value = false;
              console.error("saveOrUpdate error: ", err);
            });
        } else {
          return false;
        }
      });
    };

    // 打开弹框
    const open = (orgId, row) => {
      if (row) {
        Object.keys(form).forEach((item) => {
          form[item] = row[item];
        });
        isEdit.value = true;
      } else {
        isEdit.value = false;
      }
      form.orgId = orgId;
      visible.value = true;
    };

    // 关闭弹框
    const close = () => {
      if (confirmBtnLoading.value || dialogLoading.value) {
        return;
      }
      resetData();
      visible.value = false;
    };

    // 重置数据
    const resetData = () => {
      // 重置表单校验
      formRef.value && formRef.value.resetFields();
      // 重置表单数据
      Object.keys(form).forEach((item) => {
        form[item] = initFormData()[item];
      });
    };

    return {
      visible,
      dialogLoading,
      confirmBtnLoading,
      formRef,
      form,
      rules,
      open,
      close,
      handleConfirm,
      isEdit,
    };
  },
};
</script>

<style lang="less" scoped>
.task_form_dialog {
}
.dialog_container {
}
.dialog_footer {
}
</style>
